using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.PageFlow;
using Microsoft.Practices.PageFlow.Utils;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Globalization;
using WCSFContrib.PageFlow.Xml.Properties;

namespace WCSFContrib.PageFlow.Xml
{
    [Serializable]
    public class XmlPageFlowState : PageFlowState, ISerializable
    {
        private Dictionary<string, object> _state;
        public event EventHandler<EventArgs> ItemAdded;

        public XmlPageFlowState()
        {
            _state = new Dictionary<string,object>();
        }

        public override System.Collections.ICollection Keys
        {
            get { return _state.Keys; }
        }

        public override object this[string key]
        {
            get
            {
                if (string.IsNullOrEmpty(key))
                    throw new ArgumentNullException("key");
                if (!Contains(key))
                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.KeyDoesNotExists, key));
                return _state[key];
            }
            set
            {
                if (string.IsNullOrEmpty(key))
                    throw new ArgumentNullException("key");
                _state[key] = value;

                if (ItemAdded != null)
                    ItemAdded(this, new EventArgs());
            }
        }

        public override bool Contains(string key)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");
            return _state.ContainsKey(key);
        }

        public override void Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");
            _state.Remove(key);
        }

        #region ISerializable Members

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("state", _state);
        }

        protected XmlPageFlowState(SerializationInfo info, StreamingContext context)
        {
            _state = (Dictionary<string, object>)info.GetValue("state", typeof(Dictionary<string, object>));
        }

        #endregion
    }
}
